# gil global interpreter lock (cpython)
# python中一个线程对应于c语言中的一个线程
# gil 使得同一个时刻只有一个线程在一个cpu上执行字节码,无法将多个线程映射到多个cpu上执行

# gil会根据执行的字节码行数以及时间片释放gil,gil在遇到io的操作时候释放
import dis
# def add(a):
#     a = a + 1
#     return a
#
# print(dis.dis(add))
from threading import Lock
from threading import RLock # 可重入的锁

total = 0
# lock = Lock()
# 在同一个线程里面，可以连续调用多次acquire,一定要注意acquire的次数要和release的次数相等
lock = RLock()

def add():
    # 1.dosomething1
    # 2. IO 操作
    # dosamethon3
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        lock.acquire()
        # lock.acquire()
        total += 1
        lock.release()
        lock.release()

def desc():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total -= 1
        lock.release()

import threading
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)
thread1.start()
thread2.start()

thread1.join()
thread2.join()
print(total)

# 1.用锁会影响性能
# 2.锁会引起死锁



